﻿using ByHand.Model;
using ByHand.Services.Code;
using ByHand.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using System.Net;

namespace BackEnd.Controllers
{
    public class ProviderController : Controller
    {
        private readonly IProviderService _ProviderService;
        private readonly IProductService _ProductService;
        private readonly IProductOptionService _ProductOptionService;
        private readonly IGuuAttributeProductService _GuuAttributeProductService;

        public ProviderController(IProviderService ProviderService, IProductService ProductService, IGuuAttributeProductService GuuAttributeProductService, IProductOptionService ProductOptionService)
        {
            _ProviderService = ProviderService;
            _ProductService = ProductService;
            _GuuAttributeProductService = GuuAttributeProductService;
            _ProductOptionService = ProductOptionService;
        }

        public ActionResult Index(string page, string filter)
        {
            if (string.IsNullOrWhiteSpace(page))
            {
                page = "1";
            }
            ViewData["tableindex"] = new { page = page, pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage), filter = filter };
            return View();
        }

        public ActionResult TableProvider(int page, int pagesize, string filter)
        {
            int total = 0;
            pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage);
            if (page == 0)
            {
                page = 1;
            }
            var model = new List<Provider>();
            if (!string.IsNullOrWhiteSpace(filter))
            {
                model = _ProviderService.GetByPageFilter(page, pagesize, out total, filter);
                ViewData["filter"] = filter;
            }
            else
            {
                model = _ProviderService.GetByPage(page, pagesize, out total);
            }
            if ((total % pagesize) > 0)
            {
                ViewData["total"] = (total / pagesize) + 1;
            }
            else
            {
                ViewData["total"] = total / pagesize;
            }

            ViewData["curpage"] = page;
            ViewData["nextpage"] = page + 1;
            ViewData["prepage"] = page - 1;
            //ViewData["config"] = new TablePartial()
            //{
            //    ActionTableName = "TableProvider",
            //    ControllerName = "Provider",
            //    ActionName = "Index",
            //    NumberColumn = 4,
            //    ColsName = new[] { "Name", "Code", "Created", "Modified" },
            //    ColsValueName = new[] { "Name", "ProviderCode", "CreatedDate", "ModifiedDate" },
            //    ConfigAction = new { details = "Details", del = "Del", create = "Create", undel = "UnDel", edit = "Edit" },
            //    ConfigActionText = new { details = "Details", del = "Delete", create = "Create", undel = "Recovery", edit = "Edit" },
            //    Enable = new { details = false, del = "IsDeleted", edit = true },
            //    IsFilter = (filter == null ? false : true)
            //};
            return PartialView(model);
        }

        public ActionResult Create()
        {
            var model = new Provider();
            return View("form", model);
        }

        public ActionResult Edit(int id)
        {
            var model = _ProviderService.GetById(id);
            return View("form", model);
        }

        public ActionResult Save()
        {
            var id = Convert.ToInt32(Request.Form["id"]);
            var name = Request.Form["name"];
            var code = Request.Form["code"];
            var bgcolor = Request.Form["bgcolor"];
            var linkcolor = Request.Form["linkcolor"];
            var model = _ProviderService.GetById(id);
            if (model == null)
            {
                model = new Provider();
                model.ID = id;
            }
            model.Name = name;
            model.BgColor = bgcolor;
            model.LinkColor = linkcolor;
            model.CreatedDate = DateTime.Now;
            model.ModifiedDate = DateTime.Now;
            if (model.ID == 0 && _ProviderService.CheckCodeExist(code))
            {
                ViewBag.Result = "Code is exist.";
                return View("form", model);
            }
            if (id == 0)
            {
                model.ProviderCode = code;
                _ProviderService.Add(model);
                model = new Provider();
            }
            else _ProviderService.Update(model);
            ViewBag.Result = "Success";
            return View("form", model);
        }

        public ActionResult Del(int id)
        {
            var model = _ProviderService.GetById(id);
            if (model != null)
            {
                model.IsDeleted = true;
                model.ModifiedDate = DateTime.Now;
                _ProviderService.Update(model);
            }
            return Json(true);
        }

        public ActionResult UnDel(int id)
        {
            var model = _ProviderService.GetById(id);
            if (model != null)
            {
                model.IsDeleted = false;
                model.ModifiedDate = DateTime.Now;
                _ProviderService.Update(model);
            }
            return Json(true);
        }

        public ActionResult IsCodeExist(string code)
        {
            if (_ProviderService.CheckCodeExist(code)) return Json(true);
            else return Json(false);
        }

        public ActionResult Details(int id)
        {
            var model = _ProviderService.GetById(id);
            return View(model);
        }
        public ActionResult Merchant(int merchantID, int providerID)
        {
            var p = _ProviderService.GetById(providerID);
            p.MerchantID = merchantID;
            _ProviderService.Update(p);
            TempData["mess"] = "Thành Công";
            return RedirectToAction("Edit", "Provider", new { id = providerID });
        }
        public ActionResult Import(int merchantID)
        {
            var provider = _ProviderService.GetByMerchant(merchantID);
            int count = _ProductService.CountGuuProduct(provider.ID);
            int page = (count / 10) + 1;
            string merchantUrl = "http://test.guu.vn/api/getproducts?merchantid=" + merchantID + "&page=" + page + "&pagesize=10";
            string data = Getjsondata(merchantUrl);
            var objects = JArray.Parse(data); // parse as array  
            int result = 0;
            //partten
            string pattern = @"<.+>";
            Regex regex = new Regex(pattern);
            foreach (JObject root in objects)
            {
                foreach (KeyValuePair<String, JToken> app in root)
                {
                    if (app.Key == "ID")
                    {
                        int guuID = Convert.ToInt32((String)app.Value);
                        var p = _ProductService.GetByGuuID(guuID);
                        if (p == null)
                        {
                            p = new Product();
                            string productUrl = "http://test.guu.vn/api/getproduct?productid=" + guuID;
                            string productdata = Getjsondata(productUrl);
                            var productobject = JObject.Parse(productdata); // parse as array
                            Dictionary<String, String> dic = new Dictionary<string, string>();
                            foreach (KeyValuePair<String, JToken> ap in productobject)
                            {
                                switch ((String)ap.Key)
                                {
                                    case "ID": p.GuuID = Convert.ToInt16((String)ap.Value); break;
                                    case "Description": p.Title = regex.Replace((String)ap.Value, " "); break;
                                    case "Price": p.BasePrice = Convert.ToInt32((String)ap.Value); break;
                                    case "Status": p.GuuStatus = Convert.ToInt32((String)ap.Value); break;
                                    case "Attribute": if (ap.Value.Count() > 0)
                                        {
                                            foreach (var item in ap.Value)
                                            {
                                                var attrObject = JObject.Parse(item.ToString());
                                                GuuAttributeProduct gap = new GuuAttributeProduct();
                                                gap.GuuProductID = p.GuuID;
                                                foreach (KeyValuePair<String, JToken> i in attrObject)
                                                {
                                                    switch ((String)i.Key)
                                                    {
                                                        case "ID": gap.GuuID = Convert.ToInt32((String)i.Value); break;
                                                        case "Size": gap.Size = (String)i.Value;
                                                            if (dic.ContainsKey("Size"))
                                                            {
                                                                string value = dic["Size"] + (String)i.Value + ";";
                                                                dic["Size"] = value;
                                                            }
                                                            else
                                                            {
                                                                dic.Add("Size", (String)i.Value + ";");
                                                            }
                                                            break;
                                                        case "Color": gap.Color = (String)i.Value;
                                                            if (dic.ContainsKey("Color"))
                                                            {
                                                                string value = dic["Color"] + (String)i.Value + ";";
                                                                dic["Color"] = value;
                                                            }
                                                            else
                                                            {
                                                                dic.Add("Color", (String)i.Value + ";");
                                                            }
                                                            break;
                                                    }
                                                }
                                                _GuuAttributeProductService.Add(gap);
                                            }
                                        }
                                        break;
                                    case "Images": p.ImagePath = ""; foreach (var item in ap.Value)
                                        {
                                            byte[] d;
                                            using (WebClient client = new WebClient())
                                            {
                                                d = client.DownloadData((String)item);
                                            }
                                            if (!Directory.Exists(Utility.GetFolderImageGuuUpload((int)p.GuuID)))
                                            {
                                                Directory.CreateDirectory(Utility.GetFolderImageGuuUpload((int)p.GuuID));
                                            }
                                            string imgName = Utility.GetImageName((String)item);
                                            System.IO.File.WriteAllBytes(Utility.GetFolderImageGuuUpload((int)p.GuuID) + imgName, d);
                                            p.ImagePath += Utility.CreateImageUrl((int)p.GuuID, imgName) + ";";
                                        } break;
                                }
                            }
                            p.IsActive = false;
                            p.IsDeleted = false;
                            p.ModifiedDate = DateTime.Now;
                            p.CreatedDate = DateTime.Now;
                            p.ProviderID = provider.ID;
                            p.ProductCode = Utility.GenerateProductCode(_ProviderService.GetById(p.ProviderID).ProviderCode, (int)p.GuuID);
                            p.Price = p.BasePrice;
                            p.EndDate = DateTime.Now.AddDays(1);
                            p.Quantity = 1;
                            _ProductService.Add(p);
                            foreach (var j in dic)
                            {
                                ProductOption po = new ProductOption()
                                {
                                    ModifiedDate = DateTime.Now,
                                    CreatedDate = DateTime.Now,
                                    UserCreate = "Guu",
                                    OptionName = j.Key,
                                    OptionValue = j.Value,
                                    ProductID = p.ID
                                };
                                _ProductOptionService.Add(po);
                            }
                            result++;
                        }
                    }
                }
            }
            return Json(result);
        }
        public string Getjsondata(string URL)
        {
            System.Net.HttpWebRequest request = null;
            StreamReader responseReader = null;
            string responseData = "";

            try
            {
                request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                responseReader = new StreamReader(request.GetResponse().GetResponseStream());
                responseData = responseReader.ReadToEnd();
            }
            catch
            {
                throw;
            }
            finally
            {
                request.GetResponse().GetResponseStream().Close();
                responseReader.Close();
                responseReader = null;
            }
            return responseData;

        }
    }
}